import {Code, CodeError, Http, HttpBuilder} from "mvx-foundation";

const request = (option:WechatMiniprogram.RequestOption):
  Promise<[WechatMiniprogram.RequestSuccessCallbackResult|undefined, Error|null]>=> {

  return new Promise(resolve => {
    option.success = (res => {
      resolve([res, null])
    });
    option.fail = (err => {
      resolve([undefined, new Error(err.errMsg)])
    });
    wx.request(option)
  });
};

export class WXHttp implements Http {
  async send(): Promise<[string, CodeError]> {
    let headers:Record<string, string> = {};
    this.builder.headers().forEach(((value, key) => {
      headers[key] = value;
    }));


    const url = this.builder.getUrl();
    console.log(`${url} req `, this.builder.content());
    if (this.enableRealtimeLog) {
      wx.getRealtimeLogManager().info(`${url} req `, this.builder.content());
    }

    const [ret, err] = await request({
      url:url,
      method:<any>this.builder.method(),
      header:headers,
      data:this.builder.content(),
      dataType:"其他",
      responseType:"text",
    });

    console.log(`${url} res `, ret);
    if (this.enableRealtimeLog) {
      wx.getRealtimeLogManager().info(`${url} res `, ret);
    }

    try {
      return this.builder.responseParser({
        data: ret!.statusCode===200 ? <string>ret!.data : "",
        statusCode: ret!.statusCode??Code.ElseError,
        errMsg: ret!.errMsg,
      });
    } catch (e) {
      return ["", new CodeError("ElseError", Code.ElseError)]
    }
  }

  constructor(private builder: HttpBuilder,  private enableRealtimeLog = false) { }
}